import { ref, reactive } from "vue";
import type { FileSystemItem, ContextMenuState } from "../types/fileSystem";

// 全局单例状态
let globalUIState: any = null;

/**
 * UI交互状态管理Hook
 * 管理组件级别的UI状态，如右键菜单、对话框、重命名等
 * 使用单例模式确保全局状态一致
 */
export function useUIState() {
  if (globalUIState) {
    return globalUIState;
  }

  // 右键菜单状态
  const contextMenu = reactive<ContextMenuState>({
    visible: false,
    position: {
      x: 0,
      y: 0,
    },
  });

  // 重命名状态
  const renamingItem = ref<FileSystemItem | null>(null);
  const newName = ref("");

  // 对话框状态
  const propertiesVisible = ref(false);
  const renameDialogVisible = ref(false);

  // 右键菜单方法 - 性能优化版本
  const showContextMenu = (x: number, y: number) => {
    // 使用批量更新，减少响应式触发
    contextMenu.visible = true;
    contextMenu.position.x = x;
    contextMenu.position.y = y;
  };

  const hideContextMenu = () => {
    if (contextMenu.visible) {
      contextMenu.visible = false;
      // 不重置位置，避免菜单隐藏时跳到左上角
      // 位置保持稳定，由 ContextMenu 组件内部管理
    }
  };

  // 属性对话框方法
  const showProperties = () => {
    propertiesVisible.value = true;
    hideContextMenu();
  };

  const hideProperties = () => {
    propertiesVisible.value = false;
  };

  // 重命名方法
  const startRename = (item: FileSystemItem) => {
    renamingItem.value = item;
    newName.value = item.name;
    renameDialogVisible.value = true;
    hideContextMenu();
  };

  const confirmRename = () => {
    if (renamingItem.value && newName.value.trim()) {
      renamingItem.value.name = newName.value.trim();
    }
    cancelRename();
  };

  const cancelRename = () => {
    renamingItem.value = null;
    newName.value = "";
    renameDialogVisible.value = false;
  };

  const uiState = {
    // 状态
    contextMenu,
    renamingItem,
    newName,
    propertiesVisible,
    renameDialogVisible,

    // 方法
    showContextMenu,
    hideContextMenu,
    showProperties,
    hideProperties,
    startRename,
    confirmRename,
    cancelRename,
  };

  // 保存为全局单例
  globalUIState = uiState;

  return uiState;
}
